﻿namespace IntegrationTests.ValueConversionTests
{
    using System.Linq;
    using System.Security.Principal;
    using DirectoryServicesProtocolsExtensions.LdapConnection;
    using DirectoryServicesProtocolsExtensions.SearchRequest;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class SidConversionTests : SemanticValueConversionTest
    {
        private const string DNToTestAgainst = "CN=Administrator,CN=Users,DC=fabrikam,DC=com";
        
        [TestMethod]
        public void ObjectSidValueConversion()
        {
            // Get ObjectSID via PowerShell
            const string scriptText = 
                "Get-ADObject -identity " +
                "'" + 
                DNToTestAgainst + 
                "'" + " -properties objectSID | select -expandProperty objectSID";
            var sidAquiredByPowerShell = (SecurityIdentifier)ExecutePowerShellScript(scriptText)[0].BaseObject;           
            Assert.IsNotNull(sidAquiredByPowerShell);
            
            // Get ObjectSID via code under test
            var metaMapping = LdapConnection.GetAttributeMetaData("objectSID", LdapMetaMapFactory);
            var ldapQueryPropertiesContainer = new MockFabrikamActiveDirectoryQueryPropertiesContainer
            {
                SearchBaseDN = DNToTestAgainst,
                AttributesToLoad = new[] { "objectSID" }
            };
            
            var pagedSearchRequest = new PagedSearchRequest(ldapQueryPropertiesContainer);
            var codeResult = pagedSearchRequest.Execute(LdapConnection).Single()[0];
            var sidAquiredByCode = codeResult.Attributes["objectSID"].GetValues(metaMapping.RawDotNetTypeEquivalent)[0];
            var sidSemanticallyConvertedByCode = metaMapping.SemanticValueConversionFunction(sidAquiredByCode);

            // Converting Powershell produced result to String, since this is how SID is semantically interpreted
            Assert.AreEqual(sidAquiredByPowerShell.ToString(), sidSemanticallyConvertedByCode);
        }
    }
}
